package com.framework.utils.JLTran;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author wq
 * @date 2019/9/18 13:27
 * @description
 */
public class JltranUtil {


    //发送方私钥
    //String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/J+2whEtAu8xeqUfb24/6w/hw4IdVU9BT4U1Ec8KBozU/+yzoNzRtaNsOduSVdPUm7rOWkytC3t23e+fA9aUNQs7NSwDeyhp6pb4TcJUQCAw0CvrHIAvA6N1fr5sJllLvC/JmiZo61sbsE/Gx9qj0zlq674LS8O+atk96px42QKTQfwtBqLXHOkxHb8qb0C/2yohrunkR4Rny9oLFfWIotBu95ljdWWxOogIhGeqPrBbZZcQs3fXtROyIcFT0OlLaRiWdxdjtvQ/E7VOE4ipE5vErPIUrvMNdAgcP1rc5+qlPZOEORkspNTFNDxJgDKwFxCxE272AjhwbiffvDHOzAgMBAAECggEBAJ9HVfbPRSUbVp9JzmaT/NSmlkz3ycx/mgdKpGd1TY1XwPcfA7w6w6SmymCzEKS4X82g+GNvHY0KxxQsWl+eT3lNQaQt6vu4y3eGw2rPVGWXTxPOUke5nBGR92PTnwvOBizJd6GY5rpAXGA5/hqbvQy/JTq+d/PsbrorTu6Uccghg76n2/mg4sBwccnHhO76n9glawoDRHz8oCfxFoS/9TvfZwgUvVjJfe9LfqnoSFSnIGbfQBcx5Nr2g7mEuTsRPz20oKeTj6IzuEul+j+3ORq14xViJcDOSOyEvQftnoGa3Bw5nBVSbt3HhaiJgMgYHjZDSZh+lY0pN3kjHvNMrIECgYEA7EmgnDOOHQiSmQ5n0in0UqbAt5EqMb/+o6xKnpIasipKDC22AE1xPb1tCIlx4b7nKprKoGYrImERkS5m8zXf/oQcGOnf8YJvP8WOEtjZDi2kSozfwy4fBIPjZb0We81VlPvuoEhNwXTxDeelckBQvjOFwtlW/Zyypok0h3S4KO0CgYEAzxptzEg/0TgTsz/2kyeHVjYi2nUWLHdO3Gok4qxXiiJ4mT3ZwxWJt1bhzSmpv8XSGbVYICVGAl3xW0bLkBlc1NQ7wlAxjXVW1tOAOmtyh1efEfnr+DUHFc5UXZt1RQdqgmdP4qTmSp878kQc/9No8PqqbEpAgIdhBoy7yVTYmx8CgYArQQsqrPFd9TzI0e9FdLKqEqaCtAsyUkAt/BMo1fwXE1C8y/1eLs8FC1ETV/3F4ml0ziM7m5hX0ccieYkVCo63i72M/fslvcfZt7NbVeDeDJLfpswrcZzx+aa98BBWl28MN9Yl9zZsrJiYAAi0Unu1Zb8dvSWEhZPakpFQHpi7vQKBgQCsC42I9cAmIwqijxFcf6r7IG/lwPzRpa9ahcbskzUJqMc8rlf3qy3Do6ZjFChTCpgWCUMTOUOmdboqFG7I33jxyPl327y+gerI/dx5K4dyDYU0nsS7Zfnj0IrfVGSgGqANgpuncUtqVEutX44jq9Fy1xm6ahiZbV1Z3pGlmBl1CwKBgAscWKAwIS0y0WOCrU+YSOVfklnDw0Ym0G4elgJdzUh0yglBKR3yIzs0AQQz6VqXPxJwtD2EOUPcjQqc1xBte13+E9TdVVhq9ZMWqxbQkEfd6tOosBpNJCAj0tMGordTa2s3h3q4wrmNknmzMUx6odQ0iVeNV8A52mZy4AuRV/OX";

    //sha256 私钥
   private static String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/J+2whEtAu8xe\n" +
            "qUfb24/6w/hw4IdVU9BT4U1Ec8KBozU/+yzoNzRtaNsOduSVdPUm7rOWkytC3t23\n" +
            "e+fA9aUNQs7NSwDeyhp6pb4TcJUQCAw0CvrHIAvA6N1fr5sJllLvC/JmiZo61sbs\n" +
            "E/Gx9qj0zlq674LS8O+atk96px42QKTQfwtBqLXHOkxHb8qb0C/2yohrunkR4Rny\n" +
            "9oLFfWIotBu95ljdWWxOogIhGeqPrBbZZcQs3fXtROyIcFT0OlLaRiWdxdjtvQ/E\n" +
            "7VOE4ipE5vErPIUrvMNdAgcP1rc5+qlPZOEORkspNTFNDxJgDKwFxCxE272Ajhwb\n" +
            "iffvDHOzAgMBAAECggEBAJ9HVfbPRSUbVp9JzmaT/NSmlkz3ycx/mgdKpGd1TY1X\n" +
            "wPcfA7w6w6SmymCzEKS4X82g+GNvHY0KxxQsWl+eT3lNQaQt6vu4y3eGw2rPVGWX\n" +
            "TxPOUke5nBGR92PTnwvOBizJd6GY5rpAXGA5/hqbvQy/JTq+d/PsbrorTu6Uccgh\n" +
            "g76n2/mg4sBwccnHhO76n9glawoDRHz8oCfxFoS/9TvfZwgUvVjJfe9LfqnoSFSn\n" +
            "IGbfQBcx5Nr2g7mEuTsRPz20oKeTj6IzuEul+j+3ORq14xViJcDOSOyEvQftnoGa\n" +
            "3Bw5nBVSbt3HhaiJgMgYHjZDSZh+lY0pN3kjHvNMrIECgYEA7EmgnDOOHQiSmQ5n\n" +
            "0in0UqbAt5EqMb/+o6xKnpIasipKDC22AE1xPb1tCIlx4b7nKprKoGYrImERkS5m\n" +
            "8zXf/oQcGOnf8YJvP8WOEtjZDi2kSozfwy4fBIPjZb0We81VlPvuoEhNwXTxDeel\n" +
            "ckBQvjOFwtlW/Zyypok0h3S4KO0CgYEAzxptzEg/0TgTsz/2kyeHVjYi2nUWLHdO\n" +
            "3Gok4qxXiiJ4mT3ZwxWJt1bhzSmpv8XSGbVYICVGAl3xW0bLkBlc1NQ7wlAxjXVW\n" +
            "1tOAOmtyh1efEfnr+DUHFc5UXZt1RQdqgmdP4qTmSp878kQc/9No8PqqbEpAgIdh\n" +
            "Boy7yVTYmx8CgYArQQsqrPFd9TzI0e9FdLKqEqaCtAsyUkAt/BMo1fwXE1C8y/1e\n" +
            "Ls8FC1ETV/3F4ml0ziM7m5hX0ccieYkVCo63i72M/fslvcfZt7NbVeDeDJLfpswr\n" +
            "cZzx+aa98BBWl28MN9Yl9zZsrJiYAAi0Unu1Zb8dvSWEhZPakpFQHpi7vQKBgQCs\n" +
            "C42I9cAmIwqijxFcf6r7IG/lwPzRpa9ahcbskzUJqMc8rlf3qy3Do6ZjFChTCpgW\n" +
            "CUMTOUOmdboqFG7I33jxyPl327y+gerI/dx5K4dyDYU0nsS7Zfnj0IrfVGSgGqAN\n" +
            "gpuncUtqVEutX44jq9Fy1xm6ahiZbV1Z3pGlmBl1CwKBgAscWKAwIS0y0WOCrU+Y\n" +
            "SOVfklnDw0Ym0G4elgJdzUh0yglBKR3yIzs0AQQz6VqXPxJwtD2EOUPcjQqc1xBt\n" +
            "e13+E9TdVVhq9ZMWqxbQkEfd6tOosBpNJCAj0tMGordTa2s3h3q4wrmNknmzMUx6\n" +
            "odQ0iVeNV8A52mZy4AuRV/OX";
    //公钥
    private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvyftsIRLQLvMXqlH29uP+sP4cOCHVVPQU+FNRHPCgaM1P/ss6Dc0bWjbDnbklXT1Ju6zlpMrQt7dt3vnwPWlDULOzUsA3soaeqW+E3CVEAgMNAr6xyALwOjdX6+bCZZS7wvyZomaOtbG7BPxsfao9M5auu+C0vDvmrZPeqceNkCk0H8LQai1xzpMR2/Km9Av9sqIa7p5EeEZ8vaCxX1iKLQbveZY3VlsTqICIRnqj6wW2WXELN317UTsiHBU9DpS2kYlncXY7b0PxO1ThOIqRObxKzyFK7zDXQIHD9a3OfqpT2ThDkZLKTUxTQ8SYAysBcQsRNu9gI4cG4n37wxzswIDAQAB";

    private static String agentId="50311084";

    private static String URL="http://agentbill.jlpay.com/accountFile/download/{agentId}/{dateString}";
    //String s = "http://dev.jlpay.com/accountFile/download/50202415/20180425?sign_data=" + sign;
    public static List<Map<String, String>> download(String dateString) throws UnsupportedEncodingException {

        //字典顺序排序
        Map<String, Object> jsonObject = new TreeMap<String, Object>();
        jsonObject.put("agentId", agentId);
        jsonObject.put("date", dateString);
        //加签
        String signDate = RSA256Utils.sign256(JSON.toJSONString(jsonObject), privateKey);
        System.out.println("签名:" + signDate);
        jsonObject.put("sign", signDate);
        //发送方公钥

        String signContext = getSignJSONContext(jsonObject, "sign");
        //验签
        System.out.println(signContext);
        boolean doCheck = RSA256Utils.verify256(signContext, publicKey, jsonObject.get("sign").toString());
        System.out.println(doCheck ? "验签通过" : "验签不通过");
        //urlencode加密
        String sign = URLEncoder.encode(signDate, "utf-8");
        System.out.println("urlencode后:" + sign);
        //拼装请求地址
        String realUrl=URL.replace("{agentId}",agentId).replace("{dateString}",dateString)+"?sign_data="+sign;

        System.out.println("测试下载账单地址:" + realUrl);
        //获取mpos版的文件内容所组成的交易内容
        return getTranListByUrl(realUrl,agentId,dateString);

    }


    /**
     * 获取签名验签数据,根据ASCII码表对key进行排序，生成的数据为{"key":"value"}
     *
     * @param contextMap  数据对象
     * @param ignoresKeys 忽略字段
     * @return
     */
    public static String getSignJSONContext(Map<String, Object> contextMap, String... ignoresKeys) {
        List<String> ignoresKeyList;
        if (ignoresKeys != null) {
            ignoresKeyList = Arrays.asList(ignoresKeys);
        } else {
            ignoresKeyList = new ArrayList<>();
        }
        List<String> keys = new ArrayList<>(contextMap.keySet());
        Collections.sort(keys);
        Map<String, Object> treeMap = new TreeMap<>();
        for (String key : keys) {
            if (!ignoresKeyList.contains(key)) {
                treeMap.put(key, contextMap.get(key));
            }
        }
        return JSON.toJSONString(treeMap);
    }

    public static void main(String[] args) {
        try {
            String dateString="2019-01-21";

            JltranUtil.download(dateString.replace("-",""));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static List<Map<String, String>> getTranListByUrl(String urlParam,String agentId,String dateString) {

        HttpURLConnection con = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlParam);

            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
            InputStream inputStream = con.getInputStream();
            ZipInputStream zin = new ZipInputStream(inputStream, Charset.forName("utf-8"));
            BufferedInputStream bs = new BufferedInputStream(zin);
            byte[] bytes ;
            ZipEntry ze;

            //循环读取压缩包里面的文件
            while ((ze = zin.getNextEntry()) != null) {
                StringBuilder orginJson = new StringBuilder();
                if (ze.toString().endsWith(".txt")) {
                    //读取每个文件的字节，并放进数组
                    bytes = new byte[(int) ze.getSize()];
                    bs.read(bytes, 0, (int) ze.getSize());
                    //将文件转成流
                    InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                    br = new BufferedReader(
                            new InputStreamReader(byteArrayInputStream));
                    //读取文件里面的内容
                    String line;
                    while ((line = br.readLine()) != null) {
                        orginJson.append(line);
                    }
                    //关闭流

                    br.close();
                    String name=new String(ze.getName().replace(".txt",""));
                    System.out.println(name);
                    System.out.println("文件内容:");
                    System.out.println(orginJson.toString());
                    //符合条件则拼装
                    if(name.contains("M1")&&name.contains(agentId)&&name.contains(dateString)){
                       return getTranListByString(orginJson.toString());
                    }

                }
            }
            zin.closeEntry();
            inputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
        return null;
    }

    public static  List<Map<String,String>> getTranListByString(String content){

        String[] split = content.split("\\|");
        int count = 1;
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;

        int realCount = split.length / 12;

        for (int i = 1; i <= realCount; i++) {
            map = new HashMap<>(4);

            map.put("sn", split[(count - 1) * 12 + 1]);

            map.put("date", split[(count - 1) * 12 + 3]);

            map.put("amount", new BigDecimal(split[(count - 1) * 12 + 5]).divide(new BigDecimal("100"), 2, 4).toString());

            map.put("rate", new BigDecimal(split[(count - 1) * 12 + 6]).divide(new BigDecimal("100"), 2, 4).toString());

            list.add(map);

        }

        return list;
    }


}
